package com.cwj.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cwj.service.index;
import common.entity.course;
import common.utils.courseUtils;
import common.utils.pictUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Service
public class indexImpl implements index {
    @Resource
    ServletContext servletContext;
    @Resource
    com.cwj.dao.mapper.courseMapper courseMapper;
    static final Random RANDOM=new Random();
    @Override
    public Map<String, course> GetCourseCoverPict(Integer count) throws Exception {
        HashMap<String, course> map = new HashMap<>(count - 1);
        Integer selectCount = courseMapper.selectCount(null);
        int begin = selectCount>=count ? RANDOM.nextInt(selectCount - count) : 0;
        List<course> courses = courseMapper.selectList(new QueryWrapper<course>().last("limit " + begin + "," +( selectCount>=count ? count : selectCount)));
          for (course course : courses) {
            for (String pictType : pictUtils.pictTypes) {
                File pict = new File(servletContext.getRealPath(courseUtils.parentFile + courseUtils.CoverPict + courseUtils.setCoursePictName(course,pictType)));
                if(pict.exists()) { map.put(courseUtils.parentFile+courseUtils.CoverPict+pict.getName(),course);break;}
            }
        }

        return map;
    }
}
